package com.liu.community.advice;/*
 *@Author:Liu Xing-zhi
 *Description:
 *Date:Crated in 17:07 2021/10/11
 */

import com.alibaba.fastjson.JSON;
import com.liu.community.dto.ResponseDto;
import com.liu.community.exception.CustomerException;
import com.liu.community.exception.ErrorCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class CustomizeHandle {

  @ExceptionHandler(Exception.class)
  ModelAndView handle(Throwable ex, HttpServletRequest request, HttpServletResponse response){
      ModelAndView modelAndView = new ModelAndView();
      String contentType = request.getContentType();
      if ("application/json".equals(contentType)){
        //返回JSON
        ResponseDto responseDto ;
        if (ex instanceof CustomerException){
          responseDto = ResponseDto.errorOF((CustomerException)ex);
        }else {
          responseDto = ResponseDto.errorOF(ErrorCode.SYSTEM_ERROR);
        }
        try {
          response.setCharacterEncoding("UTF-8");
          response.setContentType("application/json");
          response.setStatus(200);
          PrintWriter writer = response.getWriter();
          writer.write(JSON.toJSONString(responseDto));
          writer.close();
        } catch (IOException e) {

        }
          return  null;
      }else {
        //跳转到错误页面
        if (ex instanceof CustomerException){
          modelAndView.addObject("message",ex.getMessage());
        }else {
          modelAndView.addObject("message","服务着火了，待会再试试吧！");
        }
        modelAndView.setViewName("error");
        return  modelAndView;
      }

  }

}
